package com.cu.employmentmanagementsystem.handler;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.fastjson.JSON;
import com.cu.employmentmanagementsystem.common.constants.AuthConstant;
import com.cu.employmentmanagementsystem.entity.Permission;
import com.cu.employmentmanagementsystem.entity.Role;
import com.cu.employmentmanagementsystem.util.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Component
public class SaPermissionHandler implements StpInterface
{
    @Autowired
    private RedisUtil redisUtil;


    @Override
    public List<String> getPermissionList(Object loginId, String loginType)
    {
        // 返回此 loginId 拥有的权限列表
        return getAuth(loginId.toString(), AuthConstant.AUTH_PERMISSION_PREFIX);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType)
    {
        // 返回此 loginId 拥有的角色列表
        return getAuth(loginId.toString(),AuthConstant.AUTH_ROLE_PREFIX);
    }

    private List<String> getAuth(String loginId, String authPrefix)
    {
        String authKey = redisUtil.buildKey(authPrefix, loginId);
        String authValue = redisUtil.get(authKey);
        if (StringUtils.isBlank(authValue))
        {
            return Collections.emptyList();
        }
        List<String> authList;
        if(AuthConstant.AUTH_ROLE_PREFIX.equals(authPrefix))
        {
            Role role = JSON.parseObject(authValue, Role.class);
            authList = Arrays.asList(role.getRoleKey());
        }
        else
        {
            List<Permission> permissionList = JSON.parseArray(authValue, Permission.class);
            authList = permissionList.stream().map(Permission::getPermissionKey).collect(Collectors.toList());
        }
        return authList;
    }

}
